const http = require('http');
const express = require('express');
require('express-async-errors');
const app = express();
const server = http.createServer(app);
const path = require('path');
const ResultJson = require('./model/ResultJson.js');
const fs = require('fs');
const AppConfig = require('./config/Appconfig.js');
const jwt = require('jsonwebtoken');
// 配置post 请求
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ limit: '30mb' }));

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Headers', 'rental_house_token,*');
  res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
  next();
});

// 设置请求拦截器
app.use((req, res, next) => {
  let pathValidatae = AppConfig.excludePath.some(item => item.test(req.path));
  if (pathValidatae) {
    // 白名单放行
    next();
  } else {
    // 不在白名单里面
    if (req.method.toUpperCase() === 'OPTIONS') {
      // 预检请求放行
      next();
    } else {
      let token = req.headers.rental_house_token;
      if (token) {
        //有token
        jwt.verify(token, AppConfig.jwtKey, (error, decoded) => {
          if (error) {
            res.status(403).json(new ResultJson(false, '当前token无效'));
          } else {
            next();
          }
        });
      } else {
        res.status(403).json(new ResultJson(false, '当前请求无权限'));
      }
    }
  }
});

//设置静态区域
app.use('/adminPhoto', express.static(path.join(__dirname, './adminPhoto')));
app.use('/roomInfo', require('./routes/roomInfoRoute.js'));
app.use('/adminInfo', require('./routes/adminInfoRoute.js'));
app.use('/stuInfo', require('./routes/stuInfoRoute.js'));
app.use('/area', require('./routes/areaRoute.js'));

//在处理全局的异常
app.use((error, req, res, next) => {
  console.log(error);
  res.status(500).json(new ResultJson(false, '服务器错误', error));
  next();
});

server.listen(8080, '0.0.0.0', () => {
  console.log('服务器启动成功');

  const deleteFile = () => {
    let excelDirPath = path.join(__dirname, './excelDir');
    let arr = fs.readdirSync(excelDirPath);
    for (let i of arr) {
      let fileCreateTime = i.split('-')[0];
      if (Date.now() - fileCreateTime > 1000 * 60 * 30) {
        fs.unlinkSync(path.join(excelDirPath, i));
      }
    }
  };
  //在服务器启动的时候就执行一次
  deleteFile();
  //接下来开启定时器，定时执行
  setInterval(deleteFile, 1000 * 60 * 30);
});
